﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Step4.Unit8.Modules;
using System.Security.Claims;

namespace Step4.Unit8.Controllers
{
    public class AccountController : Controller
    {
        private readonly SignInManager<IdentityUser> _signInManager;
        private readonly UserManager<IdentityUser> _userManager;

        public AccountController(SignInManager<IdentityUser> signInManager)
        {
             _signInManager =signInManager;
            _userManager = _signInManager.UserManager;
        }

        /// <summary>
        /// 登录视图
        /// </summary>
        /// <returns></returns>
        [AllowAnonymous] // Anonymous  允许匿名
        public IActionResult Login()
        {
            return View();
        }

        /// <summary>
        /// 登录提交方法
        /// </summary>
        [HttpPost]
        [AllowAnonymous]  // 允许任何人访问  (默认就是允许任何人访问的)
        public async Task<IActionResult> SubmitLogin(LoginViewModel model)
        {
            if (ModelState.IsValid) // 判断模型是否校验成功
            {
                // 获取用户
                var user = await _signInManager.UserManager.FindByNameAsync(model.UserName);
                if (user != null)
                {
                    //await _signInManager.SignInAsync(user,
                    //   false, // 浏览器不存储用户名密码，下次打开登录页面要重新输入
                    //   model.Pwd);
                    var result = await _signInManager.PasswordSignInAsync(user,      // 用户对象
                                                              model.Pwd, // 密码
                                                              false,     // 浏览器是否存储用户名密码
                                                              false);    // 如果登录失败是否锁定账户
                    if (result.Succeeded)
                    {
                        
                        return RedirectToAction("Index", "Home");
                    }
                    ModelState.AddModelError("", "用户名或密码不正确");
                }
                else {
                    ModelState.AddModelError("", "您输入的用户名不存在");
                }
            }
            return View("Login", model);  // 如果校验不成功，返回登录视图，用户填写信息的模型回填
        }

        /// <summary>
        /// 注册视图
        /// </summary>
        /// <returns></returns>
        public IActionResult Register()
        {

            return View();
        }


        public async Task<IActionResult> SubmitRegister(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = new IdentityUser
                {
                    UserName = model.UserName,
                    Email = model.Email
                };
                var result = await _userManager.CreateAsync(user, model.Pwd);
               
                if (result.Succeeded)
                {
                    // 后端给用户添加一个Claim ,"实际开发证Claim肯定是前端传递过来的，不能是后端写死的"
                    //await _userManager.AddClaimAsync(user,new Claim("权限管理授权声明","添加用户"));
                    await _userManager.AddClaimsAsync(user,new List<Claim> { new Claim("权限管理授权声明","添加用户"),new Claim("权限管理授权声明","删除用户") });
                    return RedirectToAction("Index", "Home");
                }
                foreach (var item in result.Errors)
                {
                    ModelState.AddModelError("", item.Description);
                }
            }
            return View("Register", model);
        }

        [Authorize]
        public async Task<IActionResult> Logout()
        {
            await _signInManager.SignOutAsync();
            return RedirectToAction("Login");
        }
    }
}
